package com.example.myapplication2;

import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Spinner2Activity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    private Spinner spinner_dialog;
    private Spinner spinner_dropdown;
    public static final String[] array={"Q","A","B"};
    public static final int[] ioc={R.color.black,R.color.teal_700,R.color.purple_200};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner2);
        spinner_dialog = findViewById(R.id.Spinner_dialog2);
        spinner_dropdown = findViewById(R.id.Spinner_dropdown2);
        ArrayList<HashMap<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < array.length; i++) {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("ioc",ioc[i]);
            hashMap.put("text",array[i]);
            list.add(hashMap);
        }
        //创建适配器,
        SimpleAdapter simpleAdapter = new SimpleAdapter(this, list,
                R.layout.image_and_text,
                new String[]{"ioc", "text"},
                new int[]{R.id.spinner_item_image, R.id.spinner_item_text});
        //设置适配器
        spinner_dialog.setAdapter(simpleAdapter);
        spinner_dropdown.setAdapter(simpleAdapter);
        //设置spinner_dialog的标题
        spinner_dialog.setPrompt("spinner_dialog的标题");
        //设置默认显示
        spinner_dialog.setSelection(0);
        spinner_dropdown.setSelection(0);
        //设置监听
        spinner_dialog.setOnItemSelectedListener(this);
        spinner_dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(Spinner2Activity.this,array[i],Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        Toast.makeText(this,array[i],Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }
}